import ResourceApi from '@/apis/system/ResourceApi'

const headerMenus = [
  {
    name: '首页',
    route: 'home'
  },
  {
    name: '查询分析',
    route: 'admin.home',
  },
  {
    name: '数据推送',
    route: 'admin.home'
  }
]
const menus = [
  {
    name: '首页',
    icon: 'el-icon-s-home',
    route: 'admin.home'
  },
  {
    name: '权限管理',
    icon: 'el-icon-setting',
    route: 'permission',
    children: [
      { name: '部门管理', icon: 'el-icon-setting', route: 'permission.department' },
      { name: '岗位管理', icon: 'el-icon-setting', route: 'permission.position' },
      { name: '用户管理', icon: 'el-icon-setting', route: 'permission.user' },
      { name: '角色管理', icon: 'el-icon-setting', route: 'permission.role' },
    ]
  },
  {
    name: '系统管理',
    route: 'system',
    icon: 'el-icon-setting',
    children: [
      { name: '系统管理', icon: 'el-icon-setting', route: 'system.system' },
      { name: '资源管理', icon: 'el-icon-setting', route: 'system.resource' },
      { name: '字典管理', icon: 'el-icon-setting', route: 'system.dictionary' },
    ],
  },
]

const state = {
  headerMenus: headerMenus,
  // 左侧菜单
  menus: menus,
  // 面包屑
  route: [{ name: 'admin.home', title: '首页' }],
  // 菜单收缩标识
  collapse: false
}

const getters = {
  getHeaderMenus (state) {
    return state.headerMenus
  },
  getMenus (state) {
    // if (state.menus.length === 0) {
    //   handlerSelectMenus()
    // }
    console.log('state.menus', state.menus)
    return state.menus
  },
  getRoute (state) {
    return state.route
  },
  getCollapse (state) {
    return state.collapse
  }
}

const mutations = {
  setHeaderMenus (state, value) {
    state.headerMenus = value
  },
  setMenus (state, menus) {
    state.menus = menus
  },
  setRoute (state, route) {
    state.route = []

    route.forEach(item => {
      if (item.meta && item.meta.menu && item.meta.menu.title) {
        state.route.push({
          name: item.name,
          title: item.meta.menu.title
        })
      }
    })
  },
  setCollapse (state, value) {
    if (value) {
      state.collapse = value
    } else {
      state.collapse = !state.collapse
    }
  }
}

const actions = {}

/**
 * 查询菜单树结构
 * @returns {Promise<void>}
 */
function handlerSelectMenus () {
  ResourceApi.selectResourceTreeList({}).then((res) => state.menus = res.data || [])
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions,
}
